#!/bin/bash

# zabbix 版本
ZABBIX_VSERSION=4

# 服务器端地址
ZabbixServer=$1

if [ -z "$ZabbixServer" ]; then
    read -p "请输入 Zabbix Server 服务器IP: " ZabbixServer
fi

# 卸载清理旧版
rpm -e zabbix-release zabbix-agent > /dev/null 2>&1

# 安装 Zabbix Agent
banben=$(cat /etc/redhat-release | grep -o [0-9]|head -n 1)

if [ $ZABBIX_VSERSION  -eq 3 ]; then 
    if [ $banben -eq 7 ];then
        yum -y install http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-1.el7.centos.noarch.rpm
    elif [ $banben -eq 6 ];then
        curl -o zabbix-release-3.4-1.el6.noarch.rpm http://repo.zabbix.com/zabbix/3.4/rhel/6/x86_64/zabbix-release-3.4-1.el6.noarch.rpm
        yum -y install zabbix-release-3.4-1.el6.noarch.rpm
        rm -f zabbix-release-3.4-1.el6.noarch.rpm
    fi
elif [ $ZABBIX_VSERSION  -eq 4 ]; then
    if [ $banben -eq 7 ];then
        yum -y install https://repo.zabbix.com/zabbix/4.2/rhel/7/x86_64/zabbix-release-4.2-1.el7.noarch.rpm
    elif [ $banben -eq 6 ];then
        curl -o zabbix-release-4.2-1.el6.noarch.rpm http://repo.zabbix.com/zabbix/4.2/rhel/6/x86_64/zabbix-release-4.2-1.el6.noarch.rpm
        yum -y install zabbix-release-4.2-1.el6.noarch.rpm
        rm -f zabbix-release-4.2-1.el6.noarch.rpm
    fi
fi

# 替换安装源
sed -i 's#repo.zabbix.com#mirrors.tuna.tsinghua.edu.cn/zabbix#g' /etc/yum.repos.d/zabbix.repo

# 安装 Zabbix
yum -y install zabbix-agent

# 配置 Zabbix Agent
local_host="linux-$(hostname -I | awk '{print $1}' | awk -F . '{print $NF}')"
sed -i "s#^Server=.*#Server=$ZabbixServer#" /etc/zabbix/zabbix_agentd.conf
sed -i "s#^ServerActive=.*#ServerActive=$ZabbixServer#" /etc/zabbix/zabbix_agentd.conf
sed -i "s#^Hostname=.*#Hostname=${local_host}#" /etc/zabbix/zabbix_agentd.conf

# 自动注册
sed -i "s/# HostMetadataItem=.*/HostMetadataItem=system.uname/" /etc/zabbix/zabbix_agentd.conf

# 启动服务
if [ $banben -eq 7 ];then
    # 放行 zabbix-agent 端口
    firewall-cmd --add-port=10050/tcp --permanent
    firewall-cmd --reload

    # 启动服务跟随系统启动
    systemctl restart zabbix-agent
    systemctl enable zabbix-agent
elif [ $banben -eq 6 ];then
    # 放行 zabbix-agent 端口
    iptables -I INPUT 35 -p tcp -m tcp --dport 10050 -m comment --comment "zabbix_agentd listen " -j ACCEPT
    service iptables save

    # 启动服务跟随系统启动
    service zabbix-agent restart
    chkconfig zabbix-agent on
fi
